//
//  DADataHandel.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/26.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DADataHandel.h"
#import "AFNetworking.h"
#import "DAAlertView.h"
#import "DAHeader.h"

#define kAcceptJson         @"text/html,application/xhtml+xml,application/json"
@interface DADataHandel()
@property(nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation DADataHandel

+(DADataHandel *)shareDADataHandel{
    static DADataHandel *networking = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        networking = [[DADataHandel alloc] init];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager.requestSerializer setValue:kAcceptJson forHTTPHeaderField:@"Accept"];
        /** 设置请求秒数*/
        manager.requestSerializer.timeoutInterval = 10;
        networking.manager = manager;
    });
    return networking;
}

+ (void)getURL:(NSString *)url parame:(id)parame result:(JSONBlock)block {
    
    [[DADataHandel shareDADataHandel].manager GET:url parameters:parame progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSData *data = responseObject;
        NSError *error = nil;
        // 数据转换 转成JSON
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
       /** 返回数据  返回的数据格式是个字典 */
        block(dic);
        if (error) {
            NSLog(@"错误信息%@", error);
            exit(0);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1001) {
            NSLog(@"请求服务器超时");
            block(@"请求服务器超时");
        } else{
            NSLog(@"%@", error);
            block(0);
        }
        
        
    }];
}

+ (void)postURL:(NSString *)url parame:(id)parame cookie:(NSString *)cookie result:(JSONBlock)block{
    NSString *urlString;
    if([url isEqualToString:DAScanQRCodeURL]){
        urlString = [DAKnowledgeUploadURL stringByAppendingString:url];
    }else{
        urlString = [DAKnowledgeURL stringByAppendingString:url];
    }
    
    [[DADataHandel shareDADataHandel].manager POST:urlString parameters:parame progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSData *data = responseObject;
        NSError *error = nil;
        // 数据转换 转成JSON
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if(!dic){
            NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
            NSLog(@"%@",result);
        }
        /** 返回数据  返回的数据格式是个字典 */
        
        if (error) {
            NSLog(@"错误信息%@", error);
        }else{
           block(dic);
        }
     
        // 缓存
        
//        NSString *path;
//        if (parame != nil) {
//            // 本地缓存
//           path = [NSString stringWithFormat:@"%ld%@.plist", [url hash], parame[@"page"]];
//        }else{
//            path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
//        }
//        
//        // 本地缓存
//      //  NSString *path = [NSString stringWithFormat:@"%ld%@.plist", [url hash], parame];
//        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//        [NSKeyedArchiver  archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
//        // 存储 存储状态
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        [userDefaults setBool:YES forKey:path];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

//        NSString *path;
//        if (parame != nil) {
//            // 本地缓存
//            path = [NSString stringWithFormat:@"%ld%@.plist", [url hash], parame[@"page"]];
//        }else{
//            path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
//        }
//        // 读取本地缓存
//      //  NSString *path = [NSString stringWithFormat:@"%ld%@.plist", [url hash],parame];
//        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
//        id result  = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
//        
//        NSData *data = result;
//        NSError *Error = nil;
        // 数据转换 转成JSON
//        if (data != nil) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&Error];
//            block(dic);
//        }else{
//            NSDictionary *dic = @{@"result": @"没有更多数据"};
//            block(dic);
//            NSLog(@"没有更多数据了");
//        }
        
        
        NSString *requestTimeOut = NSLocalizedString(@"requestServerTimeOut", nil);
        NSString *netWorkPortConnection = NSLocalizedString(@"netWorkPortConnection", nil);
        NSString *netIsNotAvailabel = NSLocalizedString(@"theCurrentNetWorkIsNotAvailabel", nil);
        
        
        if (error.code == -1001) {
            NSLog(@"请求服务器超时");
            NSDictionary *dic = @{@"result": requestTimeOut};
            block(dic);
        }
        if (error.code == -1009) {
            NSLog(@"与网络断开连接");
            NSDictionary *dic = @{@"result": netIsNotAvailabel};
            block(dic);
        }
        if (error.code == -1005) {
            NSLog(@"与网络断开连接");
            NSDictionary *dic = @{@"result": netWorkPortConnection};
            block(dic);
        }
        else{
            NSLog(@"%@", error);
           // block(dic);
        }
    }];

}














@end
